package com.itluma.myshopping.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**ddos
 * @author 飞鸟
 * @create 2021-03-05 14:25
 * 提供连接池对象
 */
public class JdbcUtils {
    private static final Properties PROPERTIES = new Properties();

    //声明一个连接池对象
    private static DataSource ds = null;

    //1.加载驱动
    static {
        //
        InputStream is = JdbcUtils.class.getResourceAsStream("/jdbc.properties");

        try {
            PROPERTIES.load(is);
            //构造具体的连接池对象：ds
            ds = DruidDataSourceFactory.createDataSource(PROPERTIES);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //2.获取连接池对象
    public static DataSource getDataSource() {
        return ds;
    }

    public static Connection getConnection() {
        try {
            return ds.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    //3.实现资源
    public static void closeAll(Connection conn, Statement stmt, ResultSet rs) {
        try {
            if (rs != null)
                rs.close();

            if (stmt != null) {
                stmt.close();
            }

            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
